/*
 * Copyright 2000-2006 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.gwt.inspections;

import com.intellij.codeInspection.*;
import com.intellij.gwt.GwtBundle;
import com.intellij.gwt.module.GwtModulesManager;
import com.intellij.gwt.module.model.GwtModule;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.psi.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author nik
 */
public class NonJREEmulationClassesInClientCodeInspection extends LocalInspectionTool {
  @NotNull
  public String getGroupDisplayName() {
    return GwtInspectionsProvider.GWT_INSPECTIONS_GROUP;
  }

  @NotNull
  public String getDisplayName() {
    return GwtBundle.message("inspection.name.classes.not.from.jre.emulation.library.in.client.code");
  }

  @NotNull
  @NonNls
  public String getShortName() {
    return "NonJREEmulationClassesInClientCode";
  }


  public boolean isEnabledByDefault() {
    return true;
  }

  @NotNull
  public HighlightDisplayLevel getDefaultLevel() {
    return HighlightDisplayLevel.ERROR;
  }


  @Nullable
  public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, boolean isOnTheFly) {
    final GwtModulesManager gwtModulesManager = GwtModulesManager.getInstance(file.getProject());
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) return null;

    final GwtModule gwtModule = gwtModulesManager.findGwtModuleByClientSourceFile(virtualFile);
    if (gwtModule == null) return null;

    final List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();

    file.accept(new PsiRecursiveElementVisitor() {
      public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
        final PsiElement resolved = reference.resolve();
        if (resolved instanceof PsiClass) {
          final GwtModulesManager gwtModulesManager1 = GwtModulesManager.getInstance(resolved.getProject());
          String name = ((PsiClass)resolved).getQualifiedName();

          final PsiFile psiFile = resolved.getContainingFile();
          if (psiFile != null) {
            final VirtualFile vFile = psiFile.getVirtualFile();
            if (vFile != null) {
              final GwtModule referencedModule = gwtModulesManager1.findGwtModuleByClientSourceFile(vFile);
              if (gwtModulesManager1.isInheritedOrSelf(gwtModule, referencedModule)) {
                return;
              }
              else if (referencedModule != null) {
                final String message = GwtBundle.message("problem.description.class.0.is.defined.in.module.1.which.is.not.inherited.in.module.2",
                                                          name, referencedModule.getQualifiedName(), gwtModule.getQualifiedName());
                problems.add(manager.createProblemDescriptor(reference, message, new InheritModuleQuickFix(gwtModule, referencedModule),
                                                             ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
                return;
              }
            }
          }

          if (!JreEmulationLibraryUtil.libraryContains(name)) {
            final String message = GwtBundle.message("problem.description.class.0.is.not.presented.in.jre.emulation.library",
                                                      ((PsiClass)resolved).getQualifiedName());
            problems.add(manager.createProblemDescriptor(reference, message, ((LocalQuickFix)null),
                                                         ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
          }
        }
        super.visitReferenceElement(reference);
      }
    });

    return problems.toArray(new ProblemDescriptor[problems.size()]);
  }

  private static class InheritModuleQuickFix implements LocalQuickFix {
    private GwtModule myGwtModule;
    private GwtModule myReferencedModule;

    public InheritModuleQuickFix(final GwtModule gwtModule, final GwtModule referencedModule) {
      myGwtModule = gwtModule;
      myReferencedModule = referencedModule;
    }

    @NotNull
    public String getName() {
      return GwtBundle.message("quick.fix.name.inherit.module.0.from.1", myGwtModule.getQualifiedName(), myReferencedModule.getQualifiedName());
    }

    @NotNull
    public String getFamilyName() {
      return getName();
    }

    public void applyFix(@NotNull final Project project, final ProblemDescriptor problemDescriptor) {
      if (!ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(myGwtModule.getModuleFile()).hasReadonlyFiles()) {
        myGwtModule.addInherits().getName().setValue(myReferencedModule.getQualifiedName());
      }
    }
  }
}
